package com.infore.dataReceiving.service.impl;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.infore.dataReceiving.constant.Constants;
import com.infore.dataReceiving.core.filter.instructions.EquipmentInfoFilter;
import com.infore.dataReceiving.dto.StatisMnNetworkDto;
import com.infore.dataReceiving.dto.WaterInstructionsDataDto;
import com.infore.dataReceiving.entity.CheckData;
import com.infore.dataReceiving.entity.EquipmentInfo;
import com.infore.dataReceiving.entity.HourData;
import com.infore.dataReceiving.entity.RealEquipmentInfo;
import com.infore.dataReceiving.entity.RealTimeData;
import com.infore.dataReceiving.entity.RecoveryData;
import com.infore.dataReceiving.entity.SpanCheckData;
import com.infore.dataReceiving.entity.ZeroCheckData;
import com.infore.dataReceiving.enums.EquipParamEnum;
import com.infore.dataReceiving.enums.LogNameEnum;
import com.infore.dataReceiving.enums.LogStatusEnum;
import com.infore.dataReceiving.enums.QualityProjectEnum;
import com.infore.dataReceiving.enums.ResultStatus;
import com.infore.dataReceiving.externalInterface.siteManage.ISiteManageService;
import com.infore.dataReceiving.outsideInterface.controller.HourDataController;
import com.infore.dataReceiving.repository.ICheckDataRepository;
import com.infore.dataReceiving.repository.IEquipmentInfoRepository;
import com.infore.dataReceiving.repository.IHourDataRepository;
import com.infore.dataReceiving.repository.IRealEquipmentInfoRepository;
import com.infore.dataReceiving.repository.IRealTimeDataRepository;
import com.infore.dataReceiving.repository.IRecoveryDataRepository;
import com.infore.dataReceiving.repository.ISpanCheckDataRepository;
import com.infore.dataReceiving.repository.IZeroCheckDataRepository;
import com.infore.dataReceiving.select.dto.QueryParamDto;
import com.infore.dataReceiving.select.util.PageObject;
import com.infore.dataReceiving.select.util.QueryCondition;
import com.infore.dataReceiving.service.IInstructionsService;
import com.infore.dataReceiving.util.DateUtil;
import com.infore.dataReceiving.util.JsonUtils;
import com.infore.dataReceiving.util.PageUtil;
import com.infore.dataReceiving.util.ResultEntity;

@Service
public class InstructionsServiceImpl implements IInstructionsService{
	
	@Autowired
	private IRealTimeDataRepository iRealTimeDataRepository;
	
	@Autowired
	private IHourDataRepository iHourDataRepository;
	
	@Autowired
	private ICheckDataRepository iCheckDataRepository;
	
	@Autowired
	private IRecoveryDataRepository iRecoveryDataRepository;
	
	@Autowired
	private IZeroCheckDataRepository iZeroCheckDataRepository;
	
	@Autowired
	private ISpanCheckDataRepository iSpanCheckDataRepository;
	
	@Autowired
	private IEquipmentInfoRepository iEquipmentInfoRepository;
	
	@Autowired
    private IRealEquipmentInfoRepository iRealEquipmentInfoRepository;
	@Autowired
    private ISiteManageService iSiteManageService;
    @Autowired
    private HourDataController hourDataController;
	
	public List<RealTimeData> queryRealTimeData(Timestamp beginTime,Timestamp endTime) {
		List<RealTimeData>  list = iRealTimeDataRepository.findByDataTimeBetweenOrderByDataTimeDesc(beginTime, endTime);
		return list;
	};
	
	public List<HourData> queryHourData(Timestamp beginTime,Timestamp endTime) {
		List<HourData>  list = iHourDataRepository.findByDataTimeBetweenOrderByDataTimeDesc(beginTime, endTime);
		return list;
	};
	
	public List<Map<String, Object>> queryRowToColHourData(String mn,String beginTime,String endTime,String pageNum,String pageSize) {
		List<String> stationlist = new ArrayList<String>(Arrays.asList(mn.split(",")));
		int a = Integer.valueOf(pageNum)-1;
		int b = Integer.valueOf(pageSize);
		int startSize = a*b+1;
		int endSize = Integer.valueOf(pageNum)*b;
		List<Map<String, Object>>  list = iHourDataRepository.findHourData(stationlist,beginTime,endTime,endSize, startSize);
		return list;
	};
	
	public Integer queryRowToColHourDataCount(String mn,String beginTime,String endTime) {
		List<String> stationlist = new ArrayList<String>(Arrays.asList(mn.split(",")));
		Integer count = iHourDataRepository.findHourDataCount(stationlist,beginTime,endTime);
		return count;
	};
	
	public List<Map<String, Object>> queryRowToColRealTimeData(String mn,String pageNum,String pageSize) {
		List<String> stationList = new ArrayList<String>(Arrays.asList(mn.split(",")));
		int a = Integer.valueOf(pageNum)-1;
		int b = Integer.valueOf(pageSize);
		int startSize = a*b+1;
		int endSize = Integer.valueOf(pageNum)*b;
		List<Map<String, Object>>  list = iHourDataRepository.findRealTimeData(stationList,endSize, startSize);
		return list;
	};
	
	@Override
	public List<Map<String, Object>> queryRowToColRealTimeData(Date startTime, Date endTime, String mn,String pageNum,String pageSize) {
        List<String> stationList = new ArrayList<String>(Arrays.asList(mn.split(",")));
        int a = Integer.valueOf(pageNum)-1;
        int b = Integer.valueOf(pageSize);
        int startSize = a*b+1;
        int endSize = Integer.valueOf(pageNum)*b;
        List<Map<String, Object>>  list = iHourDataRepository.findRealTimeDataYCS(startTime, endTime, stationList, endSize, startSize);
        return list;
    };
	
	
	public Integer queryRowToColRealTimeDataCount(String mn) {
		List<String> stationlist = new ArrayList<String>(Arrays.asList(mn.split(",")));
		Integer count = iHourDataRepository.findRealTimeDataCount(stationlist);
		return count;
	};
	
	public List<Map<String, Object>> queryRowToColRealTimeData1(String mn,String beginTime,String endTime,String pageNum,String pageSize) {
		List<String> stationlist = new ArrayList<String>(Arrays.asList(mn.split(",")));
		int a = Integer.valueOf(pageNum)-1;
		int b = Integer.valueOf(pageSize);
		int startSize = a*b+1;
		int endSize = Integer.valueOf(pageNum)*b;
		List<Map<String, Object>>  list = iRealTimeDataRepository.findRealTimeData(stationlist,beginTime,endTime,endSize, startSize);
		return list;
	};
	
	public Integer queryRowToColRealTimeDataCount1(String mn,String beginTime,String endTime) {
		List<String> stationlist = new ArrayList<String>(Arrays.asList(mn.split(",")));
		Integer count = iRealTimeDataRepository.findRealTimeDataCount(stationlist,beginTime,endTime);
		return count;
	};
	
	public List<CheckData> queryCheckData() {
		List<CheckData>  list = iCheckDataRepository.findByUpdateFlagIsNullOrderByDataTimeDesc();
		return list;
	};
	
	
	@Override
	public List<RealTimeData> queryNoFlagRealData() {
		List<String> stationCodes = new ArrayList<String>(Arrays.asList("40000000000001","40000000000002","40000000000003"));
		List<RealTimeData> list = iRealTimeDataRepository.findByUpdateFlagIsNullAndMnInOrderByDataTimeAsc(stationCodes);
		return list;
	}

	public List<RecoveryData> queryRecoveryData() {
		List<RecoveryData>  list = iRecoveryDataRepository.findByUpdateFlagIsNullOrderByDataTimeDesc();
		return list;
	};
	
	public List<ZeroCheckData> queryZeroCheckData(String factorCode) {
		List<String> factorList = new ArrayList<>();
		if (factorCode.contains(",")) {
			factorList = Arrays.asList(factorCode.split(","));
		} else {
			factorList.add(factorCode);
		}
		List<ZeroCheckData>  list = iZeroCheckDataRepository.findByFactorCodeInAndUpdateFlagIsNullOrderByDataTimeAsc(factorList);
		return list;
	};
	
	public List<SpanCheckData> querySpanCheckData(String factorCode) {
		List<String> factorList = new ArrayList<>();
		if (factorCode.contains(",")) {
			factorList = Arrays.asList(factorCode.split(","));
		} else {
			factorList.add(factorCode);
		}
		List<SpanCheckData>  list = iSpanCheckDataRepository.findByFactorCodeInAndUpdateFlagIsNullOrderByDataTimeAsc(factorList);
		return list;
	}

	@Override
	public void updateZeroCheckData(List<String> list) {
		String updateFlag = "1";
		iZeroCheckDataRepository.updateZeroCheckData(updateFlag, list);
	}

	@Override
	public void updateSpanCheckData(List<String> list) {
		String updateFlag = "1";
		iSpanCheckDataRepository.updateSpanCheckData(updateFlag, list);
	}
	
	@Override
	public void updateRealData(List<String> list) {
		String updateFlag = "1";
		iRealTimeDataRepository.updateRealTimeData(updateFlag, list);
	}

	@Override
	public void updateRecoveryData(List<String> list) {
		String updateFlag = "1";
		iRecoveryDataRepository.updateRecoveryData(updateFlag, list);
	}

	@Override
	public void updateCheckData(List<String> list) {
		String updateFlag = "1";
		iCheckDataRepository.updateCheckData(updateFlag, list);
	}

	@Override
	public ResultEntity queryLogStatusData(String mn, Timestamp beginTime, Timestamp endTime, String logType, PageObject pageObject) {
		List<String> codeList = LogStatusEnum.getCodes(logType);
		if (codeList.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		boolean pageFlag = pageObject.getPageNumber() != null && pageObject.getPageSize() != null;
		List<EquipmentInfo> list = new ArrayList<EquipmentInfo>();
		Page<EquipmentInfo> page = null;
		if (pageFlag) {
			page = iEquipmentInfoRepository.findByDataTimeBetweenAndMnAndCodeInOrderByDataTimeDesc(beginTime,
					endTime, mn, codeList, pageObject.getPageRequest());
			list = page.getContent();
		} else {
			list = iEquipmentInfoRepository.findByDataTimeBetweenAndMnAndCodeInOrderByDataTimeDesc(beginTime, endTime, mn, codeList);
		}
		for (EquipmentInfo equipmentInfo : list) {
			String code = equipmentInfo.getCode();
			String factorCode = equipmentInfo.getFactorCode();
			String explains = equipmentInfo.getExplain();
	        String[] explainsArr = explains.split("-");
			if (explains != null && explains.contains("-") && explainsArr.length == 3) {
				equipmentInfo.setName(explainsArr[1]);
				equipmentInfo.setDescribe(explainsArr[2]);
			} else {
				equipmentInfo.setName(explainsArr[1]);
				equipmentInfo.setDescribe(equipmentInfo.getInfo());
			}
			equipmentInfo.setCodeName(QualityProjectEnum.getName(factorCode));
		}
		if (pageFlag) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(PageUtil.pageConvert(page));
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
	}

    @Override
    public ResultEntity queryEquipmentParam(String mn, String factorCode) {
        List<String> codes = LogStatusEnum.ONLINE_MONITOR_PARAM.getCodes();
        List<RealEquipmentInfo> list = iRealEquipmentInfoRepository.findByMnAndFactorCodeAndCodeInOrderByCodeDesc
                (mn, factorCode, codes);
        EquipParamEnum eenmu = null;
        for (RealEquipmentInfo equipmentInfo : list) {
            String code = equipmentInfo.getCode();
            eenmu = EquipParamEnum.getDesc(code);
            equipmentInfo.setCodeName(equipmentInfo.getInfo());
            if(eenmu != null) {
                equipmentInfo.setName(LogNameEnum.getMsg(code));
                equipmentInfo.setDescribe(eenmu.getDesc());
                equipmentInfo.setCodeName(equipmentInfo.getInfo() + " " +eenmu.getUnit());
            }
        }
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
    }
    
    @Override
    public ResultEntity queryEquipmentInfos(String mn, List<String> factorCodes, List<String> codes) {
        List<RealEquipmentInfo> list = iRealEquipmentInfoRepository.findByMnAndFactorCodeInAndCodeInOrderByCodeDesc
                (mn, factorCodes, codes);
        //Object obj = EquipmentInfoFilter.equipmentMap.get(code);
        String desc = null;
        Map<String, Map<String,RealEquipmentInfo>> result = new HashMap<>();
        for (RealEquipmentInfo equipmentInfo : list) {
            String factorCode = equipmentInfo.getFactorCode();
            String code = equipmentInfo.getCode();
            equipmentInfo.setCodeName(equipmentInfo.getInfo());
            equipmentInfo.setName(LogNameEnum.getMsg(code));
            Object obj = EquipmentInfoFilter.equipmentMap.get(code);
            if( obj == null)
                continue;
            if(obj instanceof String) {
                equipmentInfo.setDescribe(equipmentInfo.getInfo());
            }else if(obj instanceof Map){
                Map<String, String> map = (Map<String, String>) obj;
                desc = map.get(equipmentInfo.getInfo());
                if(desc != null) {
                    desc = desc.substring(desc.lastIndexOf("-") +1);
                }
                equipmentInfo.setDescribe(desc);
            }
            if(result.get(factorCode) == null) {
                result.put(factorCode, new HashMap<>());
            }
            if(result.get(factorCode).get(code) == null) {
                result.get(factorCode).put(code, equipmentInfo);
            }
        }
        List<Map<String, Object>> listMap = new ArrayList<>();
        Map<String, Object> mapO = null;
        for (String factorCode : factorCodes) {
            mapO = new HashMap<>();
            mapO.put("code", factorCode);
            mapO.put("codeName", QualityProjectEnum.getName(factorCode));
            mapO.put("status", result.get(factorCode));
            listMap.add(mapO);
        }
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(listMap);
    }
    
    @Override
    public ResultEntity queryEquipmentInfo(String mn, String factorCode, String code) {
        List<RealEquipmentInfo> list = iRealEquipmentInfoRepository.findByMnAndFactorCodeAndCodeInOrderByCodeDesc
                (mn, factorCode, Arrays.asList(code));
        Object obj = EquipmentInfoFilter.equipmentMap.get(code);
        String desc = null;
        for (RealEquipmentInfo equipmentInfo : list) {
            equipmentInfo.setCodeName(equipmentInfo.getInfo());
            equipmentInfo.setName(LogNameEnum.getMsg(code));
            if( obj == null)
                continue;
            if(obj instanceof String) {
                equipmentInfo.setDescribe(equipmentInfo.getInfo());
            }else if(obj instanceof Map){
                Map<String, String> map = (Map<String, String>) obj;
                desc = map.get(equipmentInfo.getInfo());
                if(desc != null) {
                    desc = desc.substring(desc.lastIndexOf("-") +1);
                }
                equipmentInfo.setDescribe(desc);
            }
        }
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
    }
    
    @Override
    public ResultEntity queryEquipmentInfo(String mn) {
        List<String> codes = LogStatusEnum.ONLINE_MONITOR_PARAM.getCodes();
        List<RealEquipmentInfo> list = iRealEquipmentInfoRepository.findByMnAndCodeInOrderByFactorCodeDesc(mn, codes);
       // //Object obj = EquipmentInfoFilter.equipmentMap.get(code);
        //String desc = null;
        for (RealEquipmentInfo equipmentInfo : list) {
            equipmentInfo.setCodeName(equipmentInfo.getInfo());
            String code = equipmentInfo.getCode();
            equipmentInfo.setName(LogNameEnum.getMsg(code));
            String fCode = equipmentInfo.getFactorCode();
            equipmentInfo.setFactorCode(QualityProjectEnum.getName(fCode));
        }
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
    }

    @Override
    public ResultEntity queryEquipFlowLogData(String mn, Timestamp t1, Timestamp t2, String factorCode) {
        List<String> yqcodes = LogStatusEnum.ONLINE_MONITOR_LOG.getCodes();
        List<String> syscodes = LogStatusEnum.DATA_GATHER_LOG.getCodes();
        List<EquipmentInfo> sysLogList = iEquipmentInfoRepository.findByDataTimeBetweenAndMnAndFactorCodeAndCodeInOrderByDataTimeAsc
                (t1, t2, mn, factorCode, syscodes);
        
        List<EquipmentInfo> yqLogList = iEquipmentInfoRepository.findByDataTimeBetweenAndMnAndFactorCodeAndCodeInOrderByDataTimeAsc
                (t1, t2, mn, factorCode, yqcodes);
        Map<String, List<EquipmentInfo>> mapInfo = new HashMap<>();
        mapInfo.put("yqLog", yqLogList);
        mapInfo.put("sysLog", sysLogList);
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(mapInfo);
    }

    @Override
    public ResultEntity queryHourDataByMnFactor(String mn, Timestamp t1, Timestamp t2, String factorCode) {
        Map<String, Object> result = new HashMap<>();
        List<HourData> list = iHourDataRepository.findByMnAndFactorCodeAndDataTimeBetweenOrderByDataTimeDesc
                                    (mn, factorCode, t1, t2);
        int length = list.size();
        List<String> times = new ArrayList<>();
        List<String> datas = new ArrayList<>();
        HourData data = null;
        String time = null;
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH");
        if(length > 0) {
            for (int i = length -1; i >= 0; i--) {
                data = list.get(i);
                time = sim.format(data.getDataTime());
                times.add(time);
                datas.add(data.getValue());
            } 
        }
        String factorName = QualityProjectEnum.getName(factorCode);
        result.put("title", factorName + " 详细情况");
        result.put("unit", QualityProjectEnum.getUnit(factorCode));
        result.put("hourData", list);
        result.put("times", times);
        result.put("datas", datas);
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(result);
    }
    
    @Override
    public ResultEntity areaProjectTrendChart() {
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String endTime = sim.format(cal.getTime());
        cal.add(Calendar.DAY_OF_MONTH, -1);
        String beginTime = sim.format(cal.getTime());
        
        List<Map<String, Object>> list = iHourDataRepository.queryAreaDataHourData(beginTime, endTime);
        Map<String,Map<String,Double>> projTimeMap = new HashMap<>();
        String dTime = null, factorCode = null;
        Double aValue = null;
        Map<String,Double> timeMap = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位  
        numberFormat.setMaximumFractionDigits(2); 
        for (Map<String, Object> map : list) {
            dTime = map.get("DTIME") == null?null:map.get("DTIME").toString(); 
            factorCode = map.get("FACTOR_CODE") == null?null:map.get("FACTOR_CODE").toString(); 
            aValue = map.get("AVALUE") == null?null:Double.valueOf(map.get("AVALUE").toString());
            if(dTime == null || factorCode == null || aValue == null )
                continue;
            if(projTimeMap.get(factorCode) == null) {
                projTimeMap.put(factorCode, new HashMap<>());
            }
            aValue = Double.valueOf(numberFormat.format(aValue));
            if(timeMap.get(dTime) == null)
                xAxis.add(dTime);
            timeMap.put(dTime, aValue);
            projTimeMap.get(factorCode).put(dTime, aValue);
        }
        
        Map<String, Object> yxis = null;
        List<Double> valueList = null;
        List<Map<String, Object>> yAxis = new ArrayList<>();
        for (QualityProjectEnum projEnum : QualityProjectEnum.values()) {
            String code = projEnum.getCode();
            yxis = new HashMap<>();
            yAxis.add(yxis);
            valueList = new ArrayList<>();
            yxis.put("name", projEnum.getName());
            yxis.put("list", valueList);
            timeMap = projTimeMap.get(code);
            if(timeMap != null) {
                for (String time : xAxis) {
                    valueList.add(timeMap.get(time));
                } 
            }
            
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("yAxis", yAxis);
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(result);
    }

    @Override
    public ResultEntity queryEquipmentInfosByh(String mn, List<WaterInstructionsDataDto> finalList) {
        // TODO Auto-generated method stub
        //获取五参数实时数据
        if(finalList == null || finalList.size() == 0) {
            return new ResultEntity(ResultStatus.ERROR, Constants.QUERY_FAILUE);
        }
        WaterInstructionsDataDto data = finalList.get(0);
        List<Map<String,Object>> result = new ArrayList<>();
        Map<String,Object> fiveParams = wrapFiveParams(data);
        result.add(fiveParams);
        String w01019 = data.getW01019();// "高锰酸盐指数数据
        if(StringUtils.isNotBlank(w01019)) {
            fiveParams = wrapParamsZt(mn, w01019, "w01019");
            result.add(fiveParams);
        }
        String w21003 = data.getW21003();// 氨氮数据
        if(StringUtils.isNotBlank(w21003)) {
            fiveParams = wrapParamsZt(mn, w21003, "w21003");
            result.add(fiveParams);
        }
        String w21001 = data.getW21001();// 总氮数据
        if(result.size() < 3 && StringUtils.isNotBlank(w21001)) {
            fiveParams = wrapParamsZt(mn, w21001, "w21001");
            result.add(fiveParams);
        }
        
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(result);
    }
    
    @Override
    public ResultEntity queryStationRealMoin(String mn) throws IOException {
        //w01019 默认采用溶解氧的分析仪状态
        Map<String, Object> yyState = wrapParamsZt(mn,"","w01019");
        List<WaterInstructionsDataDto> list =  queryMnRealDataState(mn);
        String state = "0";
        if(list != null &&  list.size() == 1) {
            state = list.get(0).getStationState();
        }
        if(state.equals("0")) {
            yyState.put("state", "离线");
            yyState.put("netlv", "10%");
            yyState.put("valv", "32%");
        }else {
            yyState.put("state", "在线");
            yyState.put("netlv", "98%");
            yyState.put("valv", "97%");
        }
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(yyState);
    }

    /**
     * 封装因子的运行状态数据
     * 
     * @author 蔡永顺
     * @return Map<String,List<Map<String,String>>>
     * @param value 值
     * @param fcode 因子编码
     * @return
     * @date 2019年11月26日上午11:01:25
     */
    private Map<String, Object> wrapParamsZt(String mn, String value, String fcode) {
        // TODO Auto-generated method stub
        String name = QualityProjectEnum.getName(fcode);
        String unit = QualityProjectEnum.getUnit(fcode);
        Map<String, Object> re = new HashMap<>();
        List<Map<String, String>> five = new ArrayList();
        re.put("code", fcode);
        re.put("name", name+" ("+value + unit+")");
        re.put("list", five);
      // List<String> codes = LogStatusEnum.ONLINE_MONITOR_STATUS.getCodes();
        List<String> codes = Arrays.asList("i12003","i12001","i11001");
        List<RealEquipmentInfo> list = iRealEquipmentInfoRepository.findByMnAndFactorCodeAndCodeInOrderByCodeDesc
                (mn, fcode, codes);
        String desc = null;
        Map<String, Map<String,RealEquipmentInfo>> result = new HashMap<>();
        Map<String, String> map2 = null;
        for (RealEquipmentInfo equipmentInfo : list) {
            map2 = new HashMap<>();
            five.add(map2);
            String factorCode = equipmentInfo.getFactorCode();
            String code = equipmentInfo.getCode();
            equipmentInfo.setCodeName(equipmentInfo.getInfo());
            equipmentInfo.setName(LogNameEnum.getMsg(code));
            Object obj = EquipmentInfoFilter.equipmentMap.get(code);
            if( obj == null)
                continue;
            if(obj instanceof String) {
                equipmentInfo.setDescribe(equipmentInfo.getInfo());
            }else if(obj instanceof Map){
                Map<String, String> map = (Map<String, String>) obj;
                desc = map.get(equipmentInfo.getInfo());
                if(desc != null) {
                    desc = desc.substring(desc.lastIndexOf("-") +1);
                }
                equipmentInfo.setDescribe(desc);
            }
            map2.put("name", equipmentInfo.getName());
            if(equipmentInfo.getName().equals("工作状态")) {
                re.put("gzState", equipmentInfo.getDescribe());
            }
            map2.put("value", equipmentInfo.getDescribe());
        }
        
        return re;
    }

    private Map<String, Object> wrapFiveParams(WaterInstructionsDataDto data) {
        //五参数数据获取
//        PH("w01001", "PH", "无量纲"),  // PH
//        WT("w01010", "水温", "℃"),  // 水温
//        DO("w01009", "溶解氧", "mg/L"),  // 溶解氧
//        EC("w01014", "电导率", "μS/cm"),  // 电导率
//        TUB("w01003", "浊度", "NTU"),  // 浊度
        Map<String, Object> re = new HashMap<>();
        List<Map<String, String>> five = new ArrayList();
        re.put("name", "五参数分析仪");
       // re.put("code", "");
        re.put("list", five);
        String w01001 = data.getW01001(); //ph
        String w01010 = data.getW01010(); //水温
        String w01009 = data.getW01009(); //溶解氧
        String w01014 = data.getW01014(); //电导率
        String w01003 = data.getW01003(); //浊度
        Map<String, String> map = new HashMap<>();
        five.add(map);
        map.put("name", "水温");
        map.put("value", w01010+"℃");
        map = new HashMap<>();
        five.add(map);
        map.put("name", "PH");
        map.put("value", w01001);
        map = new HashMap<>();
        five.add(map);
        map.put("name", "标定时间");
        map.put("value", data.getDataTime());
        map = new HashMap<>();
        five.add(map);
        map.put("name", "浊度");
        map.put("value", w01003+"NTU");
        map = new HashMap<>();
        five.add(map);
        map.put("name", "溶解氧");
        map.put("value", w01009+"mg/L");
        map = new HashMap<>();
        five.add(map);
        map.put("name", "电导率");
        map.put("value", w01014+"μS/cm");
        
        return re;
    }
    
    private List<WaterInstructionsDataDto> queryMnRealDataState(String mn) throws IOException {
        ResultEntity re = null;
        try {
            re = hourDataController.queryRealTimeData(mn, "1", "10000","all");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        HashMap<String, Object> content = (HashMap<String, Object>) re.getContent();
        List<WaterInstructionsDataDto> finalList = (List<WaterInstructionsDataDto>) content.get("dataList");
        Map<String, WaterInstructionsDataDto> dataMap2 = new HashMap<>();
        for (WaterInstructionsDataDto dto : finalList) {
            dataMap2.put(dto.getMn(), dto);
        }
      //  WaterQualityUtil.setWaterQuality(finalList);
        QueryParamDto queryParamDto = JsonUtils.readJsonFromClassPath("/queryParam/siteQueryBasic.json", QueryParamDto.class);
        QueryCondition q = new QueryCondition();
        String mnList = "stationMn", oper ="in";
        q.setOperator(Arrays.asList(oper));
        q.setProperty(Arrays.asList(mnList));
        q.setContent(Arrays.asList(mn));
        queryParamDto.setQueryCondition(q);
        ResultEntity resultEntity = iSiteManageService.queryStation(queryParamDto);
        Map<String, Object> dataMap = (Map<String, Object>)resultEntity.getContent();
        List<Map<String, Object>> siteList = (List<Map<String, Object>>)dataMap.get("dataList");
        Map<String, Map<String, Object>> siteMap = new HashMap<>();
        Map<String, Object> netMap = null;
        WaterInstructionsDataDto dto = null;
        for(Map<String, Object> map:siteList) {
            siteMap.put(map.get("stationMn").toString(), map);
            String stationMn = map.get("stationMn").toString();
            dto = dataMap2.get(stationMn);
            if(dto == null) {
                dto = new WaterInstructionsDataDto();
                finalList.add(dto);
                dto.setMn(stationMn);
                dto.setStationState("0"); //离线
                dto.setStationName(map.get("stationName").toString());
            }
        }  
        return finalList;
    }
    
    private Map<String,String> queryMnStationName(String mn){
        QueryParamDto queryParamDto;
        try {
            queryParamDto = JsonUtils.readJsonFromClassPath("/queryParam/siteQueryBasic.json", QueryParamDto.class);
        } catch (IOException e) {
            e.printStackTrace();
            return new HashMap<>();
        }
        QueryCondition q = new QueryCondition();
        String mnList = "stationMn", oper ="in";
        q.setOperator(Arrays.asList(oper));
        q.setProperty(Arrays.asList(mnList));
        q.setContent(Arrays.asList(mn));
        queryParamDto.setQueryCondition(q);
        ResultEntity resultEntity = iSiteManageService.queryStation(queryParamDto);
        Map<String, Object> dataMap = (Map<String, Object>)resultEntity.getContent();
        List<Map<String, Object>> siteList = (List<Map<String, Object>>)dataMap.get("dataList");
        Map<String,String> stationMap = new HashMap<>();
        for (Map<String, Object> map : siteList) {
            stationMap.put(map.get("stationMn").toString(), map.get("stationName").toString());
        }
        return stationMap;
    }
    
    @Override
    public ResultEntity queryMnNetworkEcharts(String stationMn, Timestamp t1, Timestamp t2) {
        if(t1.after(t2)) {
            return new ResultEntity(ResultStatus.ERROR, "开始时间不能大于结束时间");
        }
        List<Map<String,Object>> list = iHourDataRepository.queryStatisMnsHourData(stationMn, t1, t2);
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Integer> stationDurationMap = new HashMap<>();
        for (Map<String,Object> hourData : list) {
            Date date =  (Date) hourData.get("DATA_TIME");
            String time = sim.format(date);
            int num = stationDurationMap.get(time) == null ?0 :stationDurationMap.get(time);
            stationDurationMap.put(time, num +1);
        }
        Calendar c = Calendar.getInstance();
        c.setTime(t1);
        Map<String,Object> result = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<Integer> zxList = new ArrayList<>();
        List<Integer> dxList = new ArrayList<>();
        while(c.getTime().before(t2)) {
            String time = sim.format(c.getTime());
            xAxis.add(time);
            int num = stationDurationMap.get(time) == null ?0 :stationDurationMap.get(time);
            int lx = 24 - num;
            dxList.add(lx);
            zxList.add(num);
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        result.put("xAxis", xAxis);
        List<Map<String,Object>> series = new ArrayList<>();
        Map<String,Object> serie = new HashMap<>();
        serie.put("name", "在线时长");
        serie.put("type", "line");
       // serie.put("yAxisIndex", 1);
        serie.put("data", zxList);
        series.add(serie);
        serie = new HashMap<>();
        serie.put("name", "掉线时长");
        serie.put("type", "line");
      //  serie.put("yAxisIndex", 1);
        serie.put("data", dxList);
        series.add(serie);
        
        result.put("series", series);
        result.put("legend", new String[]{"在线时长", "掉线时长"});
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(result);
    }
    
    @Override
    public ResultEntity queryMnNetworkStatisLv(String stationMn, Timestamp t1, Timestamp t2) {
        if(t1.after(t2)) {
            return new ResultEntity(ResultStatus.ERROR, "开始时间不能大于结束时间");
        }
        List<Map<String,Object>> list = iHourDataRepository.queryStatisMnsHourData(stationMn, t1, t2);
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Integer> stationDurationMap = new HashMap<>();
        for (Map<String,Object> hourData : list) {
            Date date =  (Date) hourData.get("DATA_TIME");
            String time = sim.format(date);
            int num = stationDurationMap.get(time) == null ?0 :stationDurationMap.get(time);
            stationDurationMap.put(time, num +1);
            
        }
        Map<String,String> stationMap = queryMnStationName(stationMn);
        Calendar c = Calendar.getInstance();
        c.setTime(t1);
        List<StatisMnNetworkDto> resultNet = new ArrayList<>();
        StatisMnNetworkDto net = null;
        while(c.getTime().before(t2)) {
            String time = sim.format(c.getTime());
            net = new StatisMnNetworkDto();
            net.setStationName(stationMap.get(stationMn));
            net.setMn(stationMn);
            resultNet.add(net);
            net.setLastTime(time);
            int num = stationDurationMap.get(time) == null ?0 :stationDurationMap.get(time);
            int lx = 24 - num;
            net.setZxNum(num);
            net.setLxNum(lx);
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(resultNet);
    }
    
    @Override
    public ResultEntity queryMnsNetworkStatisLv(String mns, String type, Timestamp t1, Timestamp t2) {
        List<WaterInstructionsDataDto> finalList = null;
        try {
            finalList = queryMnRealDataState(mns);
        } catch (IOException e) {
            return new ResultEntity(ResultStatus.ERROR, Constants.QUERY_FAILUE);
        }
        
        if(t1.after(t2)) {
            return new ResultEntity(ResultStatus.ERROR, "开始时间不能大于结束时间");
        }
        //两个时间相差多少小时
        int hours = DateUtil.diffHours(t1, t2) + 1;
        List<String> stationList = Arrays.asList(mns.split(","));
        List<Map<String,Object>> list = iHourDataRepository.queryStatisMnsHourDataNum(stationList, t1, t2);
        //统计站点的在线时长与离线时长
       // Map<String, Integer> stationMap2 = new HashMap<>();
        //站点在线
        Map<String, Integer> stationDurationMap = new HashMap<>();
       // SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH");
        for (Map<String,Object> hourData : list) {
            String mn = hourData.get("MN").toString();
            int num =  hourData.get("NUM") == null ? 0 : Integer.valueOf(hourData.get("NUM").toString());
            stationDurationMap.put(mn, num);
            
        }
        List<StatisMnNetworkDto> resultNet = new ArrayList<>();
        for (WaterInstructionsDataDto data : finalList) {
            String state = data.getStationState();
            String mn = data.getMn();
            StatisMnNetworkDto net = null;
            if(StringUtils.isBlank(type) || type.equals("all")) {
                //返回所有
                net = new StatisMnNetworkDto();
            }else if(type.equals("1")){
                if(!state.equals("0")) {
                    net = new StatisMnNetworkDto();
                }
            }else if(type.equals("0")) {
                if(state.equals("0")) {
                    net = new StatisMnNetworkDto();
                }
            }
            if(net != null) {
                net.setMn(mn);
                net.setLastTime(data.getDataTime());
                net.setState(state);
                net.setStationName(data.getStationName());
                int num = stationDurationMap.get(mn) == null ? 0:stationDurationMap.get(mn);
                int lx = hours - num;
                net.setZxNum(num);
                net.setLxNum(lx);
                resultNet.add(net);
            }
            
        }
        
        return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(resultNet);
    }
	
}
